package com.g9.blog.controller;

import com.g9.blog.common.Response;
import com.g9.blog.common.Result;
import com.g9.blog.entity.Article;
import com.g9.blog.entity.ArticleLike;
import com.g9.blog.entity.Users;
import com.g9.blog.service.ArticleService;
import com.g9.blog.service.LikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Auther: Graycat
 * @Date: 2020/9/11 15:52
 * Create by lwj.
 */

@RestController
@Transactional
public class LikeController {

    @Autowired
    private ArticleService articleService;
    @Autowired
    private LikeService likeService;

    // 用户点赞时创建关联表并在 likecount + 1   (给文章点赞)
    @PostMapping("/like")
    public Result giveItLike( ArticleLike like ){
        List<Article> article = articleService.findAllById( like.getArticleId() );
        if (article.size()==0){
            return Response.makeErrRsp("无此文章。");
        }
        //判断是否已经点过赞了。
        List<ArticleLike> likes = likeService.ifLikeOrNot(like.getArticleId(),like.getUserId());
        if (likes.size()!=0){
            return Response.makeErrRsp("已经点过赞辣。");
        }
        //点赞数+1 并保存关联表
        article.get(0).setLikeCount(article.get(0).getLikeCount()+1);
        articleService.save(article.get(0));    //--
        likeService.save(like);
        return Response.makeOKRsp();
    }

    // 根据用户id返回它点赞过的文章。
    @GetMapping("/like/byuserid/{userId}")
    public Result getLikeArticleByUserId( @PathVariable int userId ){
        List<Article> articleList  = articleService.getUserLikeArticleByUserId( userId );
        if (articleList==null||articleList.size()==0){
            return Response.makeErrRsp("该用户没有点赞过文章。");
        }
        return Response.makeOKRsp(articleList);
    }

    // 根据文章id返回所喜欢的用户
    @GetMapping("/like/byarticleid/{articleId}")
    public Result getLikeByArticleId( @PathVariable int articleId ){
        List<Users> userList = articleService.getLikeUserByArticleId(articleId);
        return Response.makeOKRsp(userList);
    }

}
